import { useState, useEffect } from 'react';
import { message } from 'antd';
// import storage from 'good-storage';
import router from 'umi/router';
import { useDispatch } from 'dva';
// import { USER_INFO } from '@/utils/commonConfig';
import { qrCodeLogin, getMenuData } from '@/services/login';
import icon from '@/assets/images/login/icon-qrcode-login.png';
import styles from './index.scss';

const isProd = UMI_ENV === 'prod';

// 浙政钉
const clientId = isProd ? 'scq_fyzxl_dingoa' : 'wysc-admin_dingoa';
const LOGIN_URL = isProd
  ? 'https://fyzxl.hzsc.gov.cn/fyzxl-admin/'
  : 'http://10.18.139.33:9028/fyzxl-admin/';

export default function QRCode({}) {
  const [dingSrc, setDingSrc] = useState('');
  const dispatch = useDispatch();

  // 丁丁扫码登录
  useEffect(() => {
    // 浙政钉
    const goto = isProd
      ? `https://login-pro.ding.zj.gov.cn/oauth2/auth.htm?response_type=code&client_id=${clientId}&redirect_uri=${LOGIN_URL}&scope=get_user_info&authType=QRCODE&embedMode=true`
      : `https://login.dg-work.cn/oauth2/auth.htm?response_type=code&client_id=${clientId}&redirect_uri=${LOGIN_URL}&scope=get_user_info&authType=QRCODE&embedMode=true`;

    setDingSrc(goto);
    // 注册监听扫描事件
    const handleMessage = event => {
      if (event && event.data && event.data.code) {
        console.log('扫码后返回信息 event: ', event);
        qrCodeLogin({ code: event.data.code })
          .then(userRes => {
            if (userRes.success) {
              const logInfo = userRes?.data || {};
              const { username } = logInfo?.user;
              const infos = {
                isLogin: true,
                currentUser: logInfo?.user,
                userToken: logInfo?.token,
                permissions: logInfo?.permissions,
              };
              localStorage.setItem('loginfo', JSON.stringify(infos));
              getMenuData(username).then(res => {
                if (res?.success) {
                  const menuData = res?.data?.[0]?.children || [];
                  const { path, children: child = [] } = menuData?.[0] || {};
                  dispatch({
                    type: 'userLogin/setKeyValue',
                    payload: { key: 'menuData', val: menuData },
                  });
                  if (child?.length) {
                    router.push(child[0].path);
                  } else {
                    router.push(path);
                  }
                  const newstate = {
                    ...infos,
                    menuData,
                  };
                  localStorage.setItem('loginfo', JSON.stringify(newstate));
                }
              });
            } else {
              message.warn(userRes?.errorMsg || '登录失败');
            }
          })
          .catch(() => {
            message.warn('扫码失败');
          });
      }
    };

    if (typeof window.addEventListener !== 'undefined') {
      window.addEventListener('message', handleMessage, false);
    } else if (typeof window.attachEvent !== 'undefined') {
      window.attachEvent('onmessage', handleMessage);
    }
    return () => {
      if (typeof window.removeEventListener !== 'undefined') {
        window.removeEventListener('message', handleMessage, false);
      } else if (typeof window.detachEvent !== 'undefined') {
        window.detachEvent('onmessage', handleMessage);
      }
    };
  }, []);

  return (
    <div className={styles['qrcode-login-wrapper']} style={{ marginTop: '-27px' }}>
      <p className={styles.desc}>手机扫码登录</p>
      <div
        className={styles.code}
        style={{ width: '200px', height: '200px', margin: '10px auto 0' }}
      >
        {dingSrc && (
          <iframe
            className={styles['ding-code']}
            src={dingSrc}
            title="dding qrcode"
            style={{ width: '300px', height: '300px', top: '-88px', left: '-50px' }}
          />
        )}
      </div>
      <div className={styles.extra} style={{ margin: '70px 0 77px' }}>
        <img
          src={icon}
          alt="二维码扫描"
          width="19px"
          height="19px"
          style={{ marginRight: '6px' }}
        />
        请打开浙政钉APP扫描二维码登录
      </div>
    </div>
  );
}
